package com.problem.concurrency;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class GetAndRemoveList {
    /**
     * 1. 多线程题，写一段测试代码，已知一个list中存放n个数字，启动两个线程同时读取该list中的第一个成员，
     * * 并将其数值输出到控制台，读取之后将该list中的该成员删除掉，直至list中没有值为止，线程结束退出。
     */
    static List<Integer> list = new ArrayList<>();

    static boolean end = true;
    static Lock lock = new ReentrantLock();
//    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//    ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
//    ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();

    static {
        for (int i = 0; i < 100; i++) {
            list.add(i);
        }
        System.out.println(list);
    }

    public static void main(String[] args) {

        new Thread(() -> {
            do {
                lock.lock();
                if (list == null || list.size() == 0) {
                    end = false;
                } else {
                    System.out.println("A:"+list.get(0));
                    list.remove(0);
                }
                lock.unlock();
                try {
                    Thread.sleep(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //sout("A");
            }while (end);
        }).start();

        new Thread(() -> {
            do {
                lock.lock();
                if (list == null || list.size() == 0) {
                    end = false;
                } else {
                    System.out.println("B:"+list.get(0));
                    list.remove(0);
                }
                lock.unlock();
                try {
                    Thread.sleep(0);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //sout("B");
            }while (end);

        }).start();
    }

    static void sout(String t) {
        synchronized (list) {
           // System.out.println(t+"开始进入");
            if (list == null || list.size() ==0) {
                end = false;
                return;
            }
            System.out.println(list.get(0));
            list.remove(0);
           // System.out.println(t+"结束");
        }
    }

}
